package dsk.demo.product.util;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class QiyeVxUtil {
    private static String agentId = "1000002";
    private static String corpid = "ww730e1bd4b63f4a14";
    private static String corpsecret = "qi6AnjZ4T5E5G_o7BJneyXqvso-uFkb-pGtMGq9nwPk";
    @Autowired
    private CacheUtil cacheUtil;

    private String getAccessToken() {
        String accessToken = cacheUtil.getValue("TENGXUN_ACCESS_TOKEN");
        if (cn.hutool.core.util.StrUtil.isNotBlank(accessToken)) {
            return accessToken;
        }
        String s = HttpUtil.get("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpid + "&corpsecret=" + corpsecret);
        accessToken = JSONUtil.parseObj(s).getStr("access_token");
        if (StrUtil.isNotBlank(accessToken)) {
            cacheUtil.setValue("TENGXUN_ACCESS_TOKEN", accessToken);
            return accessToken;
        }
        return "";
    }

    // 发送信息
    public void sendMail(String message, List<String> userList) {
        try {
            String accessToken = getAccessToken();
            Map<String, Object> params = new HashMap<>();
            params.put("touser", CollectionUtil.join(userList, "|"));
            params.put("msgtype", "text");
            params.put("agentid", agentId);
            params.put("text", Collections.singletonMap("content", message));
            params.put("safe", 0);
            params.put("enable_id_trans", 0);
            params.put("enable_duplicate_check", 0);
            params.put("duplicate_check_interval", 300);

            String body = HttpUtil.createPost("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accessToken)
                    .body(JSONUtil.toJsonStr(params))
                    .execute()
                    .body();
//            log.info("企业微信返回数据:[{}]", body);
        } catch (Exception e) {

        }

    }
}
